package com.xxwy.bean.register;

import com.xxwy.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

import java.util.Map;

/**
 * 通过注解
 * spring ioc 不会重复注册
 * @author wy
 * @date 2020/4/21 13:28
 */
//@Import(Config.class)
//@ImportResource("classpath:META-INF/bean-definition-context.xml")
@ComponentScan("com.xxwy.bean.register")
public class AnnotationBeanDefinitionDemo {

  @Autowired
  private Config config;

  public AnnotationBeanDefinitionDemo() {
    System.out.println("AnnotationBeanDefinitionDemo实例化");
  }

  public static void main(String[] args) {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

    // 通过@Bean来定义

    // 通过@Component / @Configuration + @ComponentScan

    // 通过@Import方式导入

    // 通过@ImportResource

    applicationContext.register(AnnotationBeanDefinitionDemo.class);
    applicationContext.refresh();

    Map<String, Config> beans = applicationContext.getBeansOfType(Config.class);
    System.out.println(beans);

    User bean = applicationContext.getBean("ni", User.class);
    System.out.println("ni--" + bean);

    Map<String, User> userMap = applicationContext.getBeansOfType(User.class);
    System.out.println(userMap);

    AnnotationBeanDefinitionDemo demo = applicationContext.getBean(AnnotationBeanDefinitionDemo.class);
    System.out.println("config " + demo.config);
    System.out.println("@Bean, 多次调用也只会生成同一个对象吗？" + (demo.config.user() == bean));
  }

}
